#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     routes_helper
   文件功能描述 :   功能描述
   创建人 :       小钟同学
   创建时间 :          2021/6/7
-------------------------------------------------
   修改描述-2021/6/7:         
-------------------------------------------------
"""
from fastapi import FastAPI, FastAPI
from fastapi import APIRouter
# from ZtjDirImport import DirImport
from apps.utils.modules_helper import find_modules, import_string


def print_all_routes_info(app: FastAPI):
    for ro in app.routes:
        # 注意这个地方！！！！别乱玩！！这这个你就卡死了！如果没有重载机制的话！！！
        # ro.app = app
        print('name:', ro.name, '=====>', 'path:', ro.path,'methods:')


# 通过模块的属性值来导入---注意是模块 不是__init
def register_nestable_blueprint(app=None, project_name=None, api_name='api', key_attribute='bp', hongtu='hongtu'):
    '''
    自动的导入的蓝图模块
    :param app:
    :return:
    '''
    if not app:
        import warnings
        warnings.warn('路由注册失败,需要传入Flask对象实例')
        return None
    if project_name:
        # include_packages 这个设置为True很关键，它包含了 检测 对于的_init__内的属性，这个对于外层的遍历的来说很关键
        modules = find_modules(f'{project_name}.{api_name}', include_packages=True, recursive=True)
        for name in modules:
            module = import_string(name)
            if hasattr(module, key_attribute):
                # apps.register_blueprint(module.mmpbp)
                # lantu = getattr(module,key_attribute)
                # print('sdasda',getattr(module,key_attribute).__dict__)
                app.include_router(getattr(module, key_attribute))
                # apps.register_blueprint(getattr(module,key_attribute))
            if hasattr(module, hongtu): pass
            # print('符合紅土', name)
            # getattr(module, hongtu).register(lantu)

    else:
        import warnings
        warnings.warn('路由注册失败,外部项目名称还没定义')


def register_nestable_blueprint_for_log(app=None, project_name=None, api_name='api',scan_name='api', key_attribute='bp', hongtu='hongtu'):
    '''
    自动的导入的蓝图模块
    :param app:
    :return:
    '''
    if not app:
        import warnings
        warnings.warn('路由注册失败,需要传入Fastapi对象实例')
        return None
    if project_name:
        # include_packages 这个设置为True很关键，它包含了 检测 对于的_init__内的属性，这个对于外层的遍历的来说很关键
        modules = find_modules(f'{project_name}.{api_name}', include_packages=True, recursive=True)
        from apps.ext.logger.contexr_logger_route import ContextLogerRoute
        for name in modules:
            module = import_string(name)
            # 只找某个模块开始的，避免无意义的其他扫描
            if not name.endswith(scan_name):
                continue

            if hasattr(module, key_attribute):
                # apps.register_blueprint(module.mmpbp)
                # lantu = getattr(module,key_attribute)
                router = getattr(module, key_attribute)
                # 已经全局挂载还需要吗？
                # router.route_class = ContextLogerRoute
                app.include_router(router)
                # apps.register_blueprint(getattr(module,key_attribute))
            if hasattr(module, hongtu): pass
            # print('符合紅土', name)
            # getattr(module, hongtu).register(lantu)

    else:
        import warnings
        warnings.warn('路由注册失败,外部项目名称还没定义')


class RoutesHelper:

    def __init__(self, fast_api: FastAPI):
        self.fast_api = fast_api

    def include_routes(self, routes):
        """包含路由"""
        for route in routes:
            self.include_route(route)

    def include_route(self, route):
        """包含路由"""
        if isinstance(route, dict):
            self.fast_api.include_router(
                *route.get('args', []),
                **route.get('kwargs', {}),
            )
        elif isinstance(route, APIRouter):
            self.fast_api.include_router(route)

    def load_package(self, package):
        """加载路由"""
        self.load_routes(package.__path__)

    def load_routes(self, directories):
        """加载路由"""
        for directory in directories:
            print("当前文件夹")
            self.load_route(directory)

    def load_route(self, directory):
        """加载路由"""
        routes = []
        modules = DirImport('routes', directory).all()
        print("当前所有的模块：", modules)
        for name, module in modules.items():
            if hasattr(module, 'RouterParams'):
                route = getattr(module, 'RouterParams')
                if isinstance(route, dict):
                    routes.append(route)
            elif hasattr(module, 'Router'):
                route = getattr(module, 'Router')
                if isinstance(route, APIRouter):
                    routes.append(route)
        self.include_routes(routes)
